package com.czkevin.wusan.items;

import com.czkevin.cif.BaseItem;
import com.czkevin.cif.CIFItemInstance;
import com.czkevin.cif.CustomItemFramework;
import com.czkevin.wusan.listeners.ItemSwitchListener;
import de.tr7zw.nbtapi.NBTCompound;
import de.tr7zw.nbtapi.NBTContainer;
import de.tr7zw.nbtapi.NBTEntity;
import de.tr7zw.nbtapi.NBTList;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import org.bukkit.Material;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public abstract class BaseWuSanItem extends BaseItem {

    private static final String DISPLAY_NAME = "\u00a7d《\u00a76五年高考三年模拟 \u00a7d%s\u00a7d》";

    public static final String NBT_ANWSERS_RIPPED = "AnswersRipped";

    /**
     * NBT的标志，代表这个物品是使用而丢出来而不是玩家丢出来的。
     */
    public static final String NBT_THROWN_WUSAN = "ThrownWusan";

    public static final String NBT_THROWN_TIMESTAMP = "ThrownTimestamp";

    @Override
    public final String getDisplayName(NBTCompound nbtCompound) {
        String n = String.format(DISPLAY_NAME, getSubject());
        if(isAnswersRipped(nbtCompound)) {
            n += " \u00a77(\u00a7c答案已被撕掉\u00a77)";
        }
        return n;
    }

    @Override
    public List<String> getLore(CIFItemInstance instance) {
        final boolean ripped = isAnswersRipped(instance != null ? instance.data : null);
        return ripped ?
            Collections.singletonList("\u00a7c答案已经被撕去，威力范围翻倍！") :
            Arrays.asList("\u00a76可以使用答案撕去器将答案撕掉，", "\u00a76威力范围翻倍");
    }

    public final boolean isAnswersRipped(NBTCompound data) {
        if(data == null || !data.hasKey(NBT_ANWSERS_RIPPED)) return false;
        return data.getBoolean(NBT_ANWSERS_RIPPED);
    }

    public abstract String getSubject();

    @Override
    public final boolean isBlock() {
        return false;
    }

    private static final Random RANDOM = new Random();
    private static String randomString(int len) {
        StringBuilder sb = new StringBuilder(len);
        for(int i = 0; i < len; i++) {
            sb.append(
                RANDOM.nextBoolean() ?
                    (char)(RANDOM.nextInt('Z')+'A') :
                    (char)(RANDOM.nextInt('z') + 'a')
            );
        }
        return sb.toString();
    }

    @Override
    public void onUseInHand(CIFItemInstance instance, PlayerInteractEvent event) {
        // 必须在右手用
        if(event.getHand() != EquipmentSlot.HAND) return;
        Player player = event.getPlayer();
        ItemStack item = player.getInventory().getItemInMainHand();
        if(!ItemSwitchListener.checkWuSan(item)) return; // 如果不是五三就取消
        ItemStack cloned = item.clone();
        cloned.setAmount(1); // 只丢掉一个
        if(item.getAmount() > 1) {
            // 减去一个
            item.setAmount(item.getAmount() - 1);
            player.getInventory().setItemInMainHand(item);
        } else {
            // 清空掉
            player.getInventory().setItemInMainHand(null);
        }
        Vector vel = player.getLocation().getDirection().multiply(0.6f);
        Item entity = player.getWorld().dropItem(
            player.getEyeLocation(),
            cloned
        );
        entity.setVelocity(vel);
        entity.setGlowing(true);

        CIFItemInstance cif = CustomItemFramework.getCIFDataFromItem(cloned);

        final String name = getDisplayName(cif.data);
        entity.setCustomName(name);
        entity.setCustomNameVisible(true);

        NBTCompound nbt = new NBTEntity(entity).getPersistentDataContainer();
        nbt.setBoolean(NBT_THROWN_WUSAN, true);
        nbt.setLong(NBT_THROWN_TIMESTAMP, System.currentTimeMillis());

        entity.setPickupDelay(Integer.MAX_VALUE);

        player.spigot().sendMessage(
            ChatMessageType.ACTION_BAR,
            TextComponent.fromLegacyText("\u00a7a你丢出去了: " + name)
        );
    }

    @Override
    public final Material getModelMaterial() {
        return Material.WRITTEN_BOOK;
    }

    @Override
    public NBTContainer generateItemNBT(CIFItemInstance instance, boolean isBlock) {
        NBTContainer nbt = super.generateItemNBT(instance, isBlock);
        NBTCompound tag = nbt.getCompound("tag");
        tag.setByte("resolved", (byte) 0x01);
        tag.setInteger("generation", 1);
        tag.setString("author", "首都师范大学出版社、教育科学出版社出版");
        NBTList<String> pages = tag.getStringList("pages");
        final TextComponent text = new TextComponent(randomString(200));
        text.setObfuscated(true);
        pages.add(ComponentSerializer.toString(text));
        return nbt;
    }
}
